package com.moorror.codegenvel.common.tree.actions.gencode;

import com.intellij.openapi.vfs.VirtualFile;
import com.moorror.codegenvel.common.dialog.MRDialog;
import com.moorror.codegenvel.common.tree.MTTreeCell;
import com.moorror.codegenvel.common.tree.TreePanelMark;
import com.moorror.codegenvel.common.tree.actions.AbstractMTTreeCellSelectTreeAction;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenScene;
import com.moorror.codegenvel.utils.GuiUtils;
import com.moorror.codegenvel.utils.JacksonUtils;
import com.moorror.codegenvel.utils.ProjectUtils;
import com.moorror.codegenvel.view.window.codegen.domain.ExtractVariableColumn;
import com.moorror.codegenvel.view.window.codegen.tree.MTTreeCellCodeGenScene;
import com.moorror.codegenvel.view.window.codegen.view.DialogFormExtractVelocityTemplate;
import org.apache.commons.compress.utils.Lists;
import org.jetbrains.annotations.Nullable;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.List;
import java.util.Map;

/**
 * @Author jiyanghuang
 * @Date 2025/8/18 07:57
 */
public class GenCodeExtractVelocityTemplateCopyPathAction extends AbstractMTTreeCellSelectTreeAction {

    public GenCodeExtractVelocityTemplateCopyPathAction(TreePanelMark treePanelMark, @Nullable String text, @Nullable String description) {
        super(text, description, GuiUtils.S_SQLITE, treePanelMark);
    }

    @Override
    public void handleSelectTree(DefaultMutableTreeNode mutableTreeNode, MTTreeCell mtTreeCell) {
        if (mtTreeCell instanceof MTTreeCellCodeGenScene) {
            MTTreeCellCodeGenScene codeGenSceneCell = (MTTreeCellCodeGenScene) mtTreeCell;
            CodeGenScene codeGenScene = codeGenSceneCell.getCodeGenScene();
            Map<String, Object> jsonMap = JacksonUtils.toMapDefault(codeGenScene.getJsonContext());
            List<ExtractVariableColumn> variableColumns = Lists.newArrayList();
            for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
                ExtractVariableColumn variableColumn = new ExtractVariableColumn();
                variableColumn.setVarVelocity(entry.getKey());
                if(entry.getValue() instanceof String){
                    variableColumn.setVarReplace(entry.getValue().toString());
                }
                variableColumns.add(variableColumn);
            }
            DialogFormExtractVelocityTemplate dialog = new DialogFormExtractVelocityTemplate(treePanelMark.fetchProject(), "Extract Variable", ExtractVariableColumn.class, variableColumns, (s) -> {
                return codeGenSceneCell.addTemplate(treePanelMark.jTree(), mutableTreeNode, treePanelMark, s);
            });
            VirtualFile virtualFile = ProjectUtils.fetchVirtualFileCopyPath();
            dialog.replaceFast(treePanelMark.fetchProject(), virtualFile);
            MRDialog.ofModeLess(dialog).show();
        }
    }
}
